/*
 * Script correspondiente 
 * a crear un table a partir de formato 
 * json
 */


(function($)
{  
   $.fn.stable=function()
    {
        //construir elements options despues 
        //de elementos de iteration
        //var options= $.extend({}, defaults, options);
           
        //definicion de metodos e inicializacion
        return this.each(function()
        {
          var _$obj=$(this);  //guardamos una referencia de nuestro objeto 
          //console.log("create table function this.each" );
          //console.log("Object => "+_$obj);
            //this._$table=$("<table id='table2' width='100%' cellspacing='0' cellpading='0' ></table>")
            //.addClass('stdtable');
          

          //call to the function principal
          _createTable($(this));

        });


    }; //end $.fn.stable

    
    //Var functions
    var _$object; 
    var _$table;             //Reference to main <table> (JQuery Object)
    var _$tableBody;         //Reference to body <body> in the table object
    var _$tableRows;         //Array of all <tr> in the table 
    var _$divPagination ;  //Pagination table
    
    var _$totalRecordCount=0; 
    //var pagination
    var _$currentPage = 0;
    var _$numPerPage = 10;
    


    
    //settings de functions
   var defaults={
          listUrl : '/departamento'
        };
  
    ///////////////////////////////////////////////////////
    /// CREATE ELEMENTS DOM TABLE
    /// PRIVATE METHODS    
    var _createTable=function(object)
     {
              
            this._$object=object;
            this._$table=$("<table id='table' cellspacing='0' cellpading='0'></table>")
            .addClass('table')
            .addClass('table-sorting');
             
            _createTableHead();
            _createTableBody(); 
     };
        
   var _createTableHead=function()
      {
         $tableHead=$('<thead></thead>').
                  appendTo(this._$table);
          
          _addRowTableHead($tableHead);
      }
        
       /*Adds tr element to given thead element*/
    var _addRowTableHead=function($tableHead)
      {
           console.log("_addRowTableHead");
           $tr=$('<tr role="row"></tr>').
                appendTo($tableHead);
  
            _addRowCellTableHead($tr)
      }
       
       /**Add td element to given tr head element*/
    var _addRowCellTableHead=function($tr)
       {
      
            $td=$("<th>ID</th><th>Nombre</th><th>Descripcion</th><th rowspan='3'>Actions</th>")
                   .appendTo($tr);
            
            
            //add element table 
            //$('#divTable').append(this._$table);
       }
              
    var _createTableBody=function()
       {
           this._$tableBody=$('<tbody></tbody>')
              .appendTo(this._$table);
            _addRowTableBody(this._$tableBody);           
       
       }
       
       /* Function add Row table */
     var _addRowTableBody=function($body)
       {
           
           $.ajax({
                 type:"POST",
                 url:"departamento/getList",
                 asinc:true,
                 dataType:"json",
                 success:function(data)
                 {
                   if(data.Result='OK')
                    {
                        if(data.TotalRecordCount>0)
                            {
                                _$totalRecordCount=data.TotalRecordCount;
                                _addRecordsToTable(data.Records,$body);
                                //_paginationToTable();
                         }
                        else 
                          {
                                //_paginationToTable();
                         
                          }
                     }
                   
                 },
                 error:function(data)
                {
                    
                    console.log("error de datoss");
                }
                 
           });
       }
       
       /*********************************************************/
       /*Add a list records to table*/
      var _addRecordsToTable=function(records,$body)
       {
           
           console.log("_addRecordsToTable");
           //recore la tabla agregando los registros
           $.each(records,function(index,record)
           {
           
               $tr=$('<tr></tr>')
                  .appendTo($body);
                  ///_addRow(_createRowFromRecord(record));
                  var id_data=0;
                  var band=true;
                  for(var i in record)
                   {
                      if(band)
                      {
                         id_data=record[i];
                         band=false;
                      }
                        
                     $td=$("<td>"+record[i]+"</td>")
                         .appendTo($tr);
                      
                   }
                  
                      //edit 
                      $td=$("<td>"+
                             "<a  href='#' id='edit' data-id="+id_data+">"+
                             "<img alt='Edit'></a>"+
                             "<a  href='#' id='delete' data-id="+id_data+">"+
                             "<img alt='Delete'></a>"+
                             "</td>")
                         .appendTo($tr);
           })
           
            

              console.log("informacion");
             //add elements
             this._$table.appendTo(this._$object);
             //add content in table
             
                     //Create la pagination con plugin tablePagination
            console.log("Pagination en script");
            $('tbody tr:odd', $(this._$object)).hide(); //hiding rows for test
            var options = {
            currPage : 2, 
            ignoreRows : $('tbody tr:odd', $('#table')),
            optionsForRows : [2,3,5],
            rowsPerPage : 5
            }
          
            $(this._$object).tablePagination(options);
          

       }


})(jQuery);